<template>
  <div class="shop-category">
    <!-- 左侧滑动菜单 -->
    <div class="category_feaceBox" v-show="isShowType">
      <div class="category_boxSize" @click="hizeBox()"></div>
      <div class="category_feace_ul">
        <div class="feace_title">更多分类</div>
        <div class="face_li_box">
          <div class="face_li box_flex" @click="selectItem('更多分类', '-1')">
            <!-- 点选方法 -->
            <div
              class="face_li_con"
              :class="selectActiveCon == '更多分类' ? 'select_active' : ''"
            >全部分类</div>
            <img
              src="https://oss-frakiss.oss-cn-chengdu.aliyuncs.com/icon/mini_images/right_icon_active.png"
              v-if="selectActiveCon == '更多分类'"
              class="face_li_img"
              alt
            />
            <img
              src="https://oss-frakiss.oss-cn-chengdu.aliyuncs.com/icon/mini_images/right_icon.png"
              v-else
              class="face_li_img"
              alt
            />
          </div>
        </div>
        <div class="face_li_box">
          <div class="face_li box_flex" v-for="(item, index) in getSliderList" :key="index" @click="selectItem(item, index)">
            <!-- 点选方法 -->
            <div
              class="face_li_con"
              :class="selectActiveCon == item.name ? 'select_active' : ''"
            >{{ item.name }}</div>
            <img
              src="https://oss-frakiss.oss-cn-chengdu.aliyuncs.com/icon/mini_images/right_icon_active.png"
              v-if="selectActiveCon == item.name"
              class="face_li_img"
              alt
            />
            <img
              src="https://oss-frakiss.oss-cn-chengdu.aliyuncs.com/icon/mini_images/right_icon.png"
              v-else
              class="face_li_img"
              alt
            />
          </div>
        </div>
      </div>
    </div>
    <Banner :banners="shopBanner" v-if="shopBanner && shopBanner.length" />

    <!-- 排序逻辑 -->
    <div class="hot-recommend" v-if="shopId">
      <!-- selectActiveCon -->
      <LineTitle :value="selectActiveCon" :hasPad="true" />
      <!-- <LineTitle :value="this.mode === 'bridal' ? '所有套系' : '所有商品'" :hasPad="true" /> -->
    </div>
    <div class="hot-recommend" @click="openSlideMenu" v-else>
      <LineTitle :value="selectActiveCon" :hasPad="true" />
    </div>

    <van-search v-model="search" placeholder="点击输入搜索" />
    <div class="shop-category__filter text-small">
      <wx-picker
        class="shop-category__filter-type"
        :range="sortOptions"
        range-key="text"
        :value="sortIndex"
        mode="selector"
        @change="onChangeSort"
        @cancel="onCancelSort"
      >
        <div class="select" :class="{ 'primary-color bor-bottom': selectType === 'sort' }">
          <span class="text">{{ selectName ? selectName : "排序" }}</span>
          <span class="icon" :class="{ 'invert primary-color': selectType === 'sort' }">&#xeb6d;</span>
        </div>
      </wx-picker>
      <span class="shop-category__filter-type" @click="showFilter = true">
        <span class="icon">&#xe876;</span> 筛选
      </span>
      <!-- <SelectBox @sort="onChangeSort" @range="onChangeRange" /> -->
    </div>
    <!-- 模板有修改 -->
    <div class="goods-box">
      <div class="good clearfix" v-if="productList.length">
        <ProductListItem
          v-for="(item, index) in productList"
          :key="index"
          :name="item.name"
          :cover="
            item.list_cover
              ? item.list_cover
              : Array.isArray(item.hot_cover)
              ? item.hot_cover[0]
              : item.hot_cover
          "
          :show-tag="false"
          :price="item.price"
          :display-price="item.display_price"
          :read-number="item.visitor || 0"
          :share-number="item.share_number || 0"
          @click="onClickProduct(item)"
        ></ProductListItem>
      </div>
      <ListEmpty v-else></ListEmpty>
    </div>
    <!-- 新增：没有更多数据了 -->
    <div class="no-more" v-if="productList.length && productWrap.loaded">没有更多数据了</div>
    <!-- <ListEmpty v-if="productList.length === 0" /> -->

    <!-- 过滤器 -->
    <div v-if="showFilter" class="popup-container filter-popup" @click="showFilter = false">
      <div class="popup popup--pos-right" @click.stop>
        <div class="filter-popup__title">价格区间</div>
        <div class="filter-popup__input-wrap">
          <input
            type="number"
            v-model="tempFilter.min"
            placeholder="最低价"
            class="filter-popup__input"
          />
          <span class="filter-popup__line">&nbsp;——&nbsp;</span>
          <input
            type="number"
            v-model="tempFilter.max"
            placeholder="最高价"
            class="filter-popup__input"
          />
        </div>
        <!-- 品牌 -->
        <!-- <template v-if="category && category.length">
          <div class="filter-popup__title">{{ type }}</div>
          <div v-for="(row, rowIndex) in category" :key="rowIndex" class="filter-popup__row">
            <div class="filter-popup__item-wrap">
              <div
                v-if="row[0]"
                class="filter-popup__item"
                :class="{
                  'filter-popup__item--active':
                    row[0].id === tempFilter.category,
                }"
                @click="onClickCategory(row[0])"
              >{{ row[0].name }}</div>
            </div>
            <div class="filter-popup__item-wrap">
              <div
                v-if="row[1]"
                class="filter-popup__item"
                :class="{
                  'filter-popup__item--active':
                    row[1].id === tempFilter.category,
                }"
                @click="onClickCategory(row[1])"
              >{{ row[1].name }}</div>
            </div>
            <div class="filter-popup__item-wrap">
              <div
                v-if="row[2]"
                class="filter-popup__item"
                :class="{
                  'filter-popup__item--active':
                    row[2].id === tempFilter.category,
                }"
                @click="onClickCategory(row[2])"
              >{{ row[2].name }}</div>
            </div>
          </div>
        </template>
        <template v-if="brand && brand.length">
          <div class="filter-popup__title">品牌</div>
          <div v-for="(row, rowIndex) in brand" :key="rowIndex" class="filter-popup__row">
            <div class="filter-popup__item-wrap">
              <div
                v-if="row[0]"
                class="filter-popup__item"
                :class="{
                  'filter-popup__item--active': row[0].id === tempFilter.brand,
                }"
                @click="onClickBrand(row[0])"
              >{{ row[0].name }}</div>
            </div>
            <div class="filter-popup__item-wrap">
              <div
                v-if="row[1]"
                class="filter-popup__item"
                :class="{
                  'filter-popup__item--active': row[1].id === tempFilter.brand,
                }"
                @click="onClickBrand(row[1])"
              >{{ row[1].name }}</div>
            </div>
            <div class="filter-popup__item-wrap">
              <div
                v-if="row[2]"
                class="filter-popup__item"
                :class="{
                  'filter-popup__item--active': row[2].id === tempFilter.brand,
                }"
                @click="onClickBrand(row[2])"
              >{{ row[2].name }}</div>
            </div>
          </div>
        </template> -->
        <div class="filter-popup__btn">
          <div
            @click="onClickSelectReset"
            class="btn btn-mobile btn-normal btn-white-red red-border"
          >重置</div>
          <div @click="onClickSelectConfirm" class="btn btn-mobile btn-normal btn-red">确定</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { api } from "@/lib/api";
import store from "@/store";
import LineTitle from "@/components/common/lineTitle.vue";
import Banner from "@/components/common/banner.vue";
import TabBox from "@/components/common/tabBox.vue";
import ProductListItem from "@/features/product/listItem.vue";
import SelectBox from "@/features/shop/selectBox.vue";
import ListEmpty from "@/components/list/listEmpty.vue";
import { Component, Vue, Watch } from "vue-property-decorator";
import { Route } from "vue-router";
import { EMPTY_LIST, ROUTE_NAME } from "@/lib/constant";
import { WatchDelay } from "@/lib/utils";

Component.registerHooks(["beforeRouteEnter"]);

@Component({
  name: "ShopCategory",
  components: {
    LineTitle,
    Banner,
    TabBox,
    ProductListItem,
    SelectBox,
    ListEmpty
    // BuyCar,
  }
})
export default class ShopCategory extends Vue {
  public realKey: any = "";
  public sortValue: any = "";
  public sortName: any = "";
  public search = "";

  public isShowType = false;
  public selectActive = 0;
  public selectActiveCon = "";

  /** 排序选项 */
  public sortOptions: ValueText[] = [
    { value: "multiple", text: "综合排序" },
    { value: "createdAt", text: "新上架" },
    { value: "priceDesc", text: "价格由高到低" },
    { value: "priceAsc", text: "价格由低到高" },
    { value: "visitor", text: "高人气" }
  ];
  /** 是否显示filter */
  public showFilter = false;
  public filter: {
    min: string;
    max: string;
    category: number;
    brand: number | null;
  } = {
    min: "",
    max: "",
    category: -1,
    brand: null
  };
  public tempFilter: {
    min: string;
    max: string;
    category: number;
    brand: number | null;
  } = {
    min: "",
    max: "",
    category: -1,
    brand: null
  };

  //  
  public type = "";

  // public get type() {
  //   return this.$route.query.type as string;
  // }
  public get mode() {
    return this.$route.query.mode;
  }
  public get shopId() {
    return this.$route.params.shopId;
  }
  /** banner */
  public get indexBanners() {
    return store.state.shop.indexBanners;
  }
  /** 店铺详情 */
  public get shopDetailMap() {
    return store.state.shop.shopDetailMap;
  }
  /** banners */
  public get bannersMap() {
    return store.state.shop.banners;
  }
  /** 商品列表 */
  public get goodProductList() {
    return store.state.good.productList;
  }
  public get goodProductMap() {
    return store.state.good.productMap;
  }
  /** 套系列表 */
  public get pkgProductList() {
    return store.state.pkg.productList;
  }
  public get pkgProductMap() {
    return store.state.pkg.productMap;
  }

  public get getSliderList() {
    return store.state.good.sliderList;
  }
  // 打开左侧菜单
  public openSlideMenu() {
    this.isShowType = true;
  }
  public hizeBox() {
    this.isShowType = false;
  }
  // 左侧菜单栏选中
  // TODO 点击菜单
  public selectItem(_item, _index) {
    if(_item == '更多分类'){
      this.filter.category = _index;
      this.tempFilter.category = _index;
      this.type = '更多分类';
      this.selectActiveCon = '全部分类';
      this.getProductList(true);
      this.isShowType = false;
    }else{
      this.filter.category = _item.name;
      this.tempFilter.category = _item.name;
      this.type = _item.name;

      this.selectActiveCon = _item.name;
      this.getProductList(true);
      this.isShowType = false;
    }
    // 获取品牌
    // this.getBrandList();
  }
  /** 店铺banner */
  public get shopBanner() {
    return this.shopId
      ? this.bannersMap[Number(this.shopId)] || []
      : this.indexBanners;
  }
  /** 店铺详情 */
  public get shopDetail() {
    return this.shopDetailMap[Number(this.shopId)];
  }
  /** 区间是否有效 */
  public get isScreenValid() {
    if (this.filter.min && this.filter.max) {
      const low = Number(this.filter.min);
      const high = Number(this.filter.max);
      return !isNaN(low) && !isNaN(high) && high > low;
    }
    return true;
  }
  /** 价格区间 */
  public get screen() {
    return this.isScreenValid
      ? {
          min: this.filter.min ? Number(this.filter.min) * 100 : "",
          max: this.filter.max ? Number(this.filter.max) * 100 : ""
        }
      : null;
  }
  /** 商品wrap */
  //  TODO productWrap
  public get productWrap() {
    if (!this.shopDetail && !this.type) {
      return EMPTY_LIST;
    }
    if (
      (this.shopDetail && this.shopDetail.is_photography) ||
      this.mode === "bridal"
    ) {
      // ${this.tempFilter.brand}_
      const key = `${this.shopId ? this.shopId : null}_${this.type}_${
        this.sortValue
      }_${JSON.stringify(this.screen)}_${this.search}`.replace("更多分类", "");
      return this.pkgProductList[key] || EMPTY_LIST;
    } else {
      // ${this.filter.brand}_
      const key = `${this.shopId ? this.shopId : null}_${
        this.type
      }_${this.filter.category >= 0 ? this.filter.category : null}_${
        this.sortValue
      }_${JSON.stringify(this.screen)}_${this.search}`.replace("更多分类", "");
      return this.goodProductList[key] || EMPTY_LIST;
    }
  }
  /** 商品列表 */
  // TODO 获取列表
  public get productList() {
    if (!this.shopDetail && !this.type) {
      return [];
    }
    if (
      (this.shopDetail && this.shopDetail.is_photography) ||
      this.mode === "bridal"
    ) {
      // 修改：边界条件处理，如果请求的商品列表为空
      if (JSON.stringify(this.pkgProductMap) === "{}") {
        return {};
      } else {
        // 修改：如果列表不为空
        return this.productWrap.list.map((id: any) => {
          return this.pkgProductMap[id];
        });
      }
    } else {
      return this.productWrap.list.map((id: any) => {
        return this.goodProductMap[id];
      });
    }
  }
  public get sortIndex() {
    return this.sortOptions.map(option => option.value).indexOf(this.sortValue);
  }
  /** 二级类别信息 */
  public get category() {
    const list = store.state.shop.category[this.type] || [];
    const result: IdName[][] = [];
    for (let i = 0, len = list.length; i < len; i = i + 3) {
      const row: IdName[] = [];
      if (list[i]) {
        row.push(list[i]);
      }
      if (list[i + 1]) {
        row.push(list[i + 1]);
      }
      if (list[i + 2]) {
        row.push(list[i + 2]);
      }
      result.push(row);
    }
    return result;
  }
  /** 品牌列表 */
  public get brand() {
    const list = store.state.good.brand[this.type] || [];
    const result: IdName[][] = [];

    for (let i = 0, len = list.length; i < len; i = i + 3) {
      const row: IdName[] = [];
      if (list[i]) {
        row.push(list[i]);
      }
      if (list[i + 1]) {
        row.push(list[i + 1]);
      }
      if (list[i + 2]) {
        row.push(list[i + 2]);
      }
      result.push(row);
    }
    return result;
  }

  @WatchDelay("search", 500)
  @Watch("search")
  public onSearch() {
    this.getProductList(true);
  }

  /**
   * 点击品牌
   */
  public onClickBrand(brand: IdName) {
    this.tempFilter.brand = brand.id;
  }
  /**
   * 点击类别
   */
  public onClickCategory(category: IdName) {
    this.tempFilter.category = category.id;
  }
  /**
   * 确认
   */
  public onClickSelectConfirm() {
    const { filter, tempFilter } = this;
    filter.min = tempFilter.min;
    filter.max = tempFilter.max;
    filter.category = tempFilter.category;
    filter.brand = tempFilter.brand;

    this.showFilter = false;
    this.getProductList(false);
  }
  public onClickSelectReset() {
    const temp = this.tempFilter;
    temp.min = "";
    temp.max = "";
    temp.category = -1;
    temp.brand = -1;
  }
  /**
   * 修改sort
   */
  public onChangeSort(e: any) {
    const option = this.sortOptions[e.detail.value];
    if (option) {
      this.sortValue = option.value;
      this.sortName = option.text;
    }
    this.getProductList(false);
    this.onCancelSort();
  }
  public onCancelSort() {
    // this.selectType = '';
  }
  // /**
  //  * 更新排序
  //  */
  // public onChangeSort(sort: any) {
  //     this.sortValue = sort.val;
  //     this.sortName = sort.name;
  //     this.getProductList();
  // }

  /**
   * 获取商品列表
   * isSwitchTab：切换分类tab为true 上拉加载更多 false
   */
  // TODO 获取列表 修改
  //
  public async getProductList(forceUpdate = true, isSwitchTab = true) {
    let getCategory = "";
    if (!this.shopDetail && !this.type) {
      return;
    }
    if (
      this.selectActiveCon == "更多分类" || this.selectActiveCon == "全部分类"
    ) {
      getCategory = "";
    } else {
      getCategory = this.selectActiveCon;
    }

    // 是何意
    if (
      (this.shopDetail && this.shopDetail.is_photography) ||
      this.mode === "bridal"
    ) {
      store.dispatch("pkg/getProductList", {
        // brand: this.tempFilter.brand,
        shopId: this.shopId ? this.shopId : null,
        // category: this.type,
        category: getCategory,
        // offset: 0
        // 修改
        offset: this.productList.length,
        count: 10,
        sort: this.sortValue,
        screen: this.screen,
        name: this.search,
        forceUpdate: true,
        // 新增
        isSwitchTab: isSwitchTab
      });
    } else {
      store.dispatch("good/getProductList", {
        // 店铺id
        shopId: this.shopId,
        brand: this.filter.brand,
        // 搜索二级分类，或者是默认的一级分类
        // category: this.type,
        // TODO 请求参数
        category: getCategory,
        categoryId: this.filter.category >= 0 ? this.filter.category : null,
        // offset: 0,
        offset: this.productList.length,
        count: 10,
        sort: this.sortValue,
        screen: this.screen,
        name: this.search,
        forceUpdate: true
      });
    }
  }

  /**
   * 点击商品
   */
  public onClickProduct(item: Product.ListItem | Pkg.ListItem) {
    if (
      (this.shopDetail && this.shopDetail.is_photography) ||
      this.mode === "bridal"
    ) {
      // api.navigateTo({
      //     url: '/pages/pkg_detail/main',
      //     query: {
      //         pkg_id: item.id,
      //     },
      // });
      // if((this.selectActiveCon == '全部分类' || this.selectActiveCon == '更多分类' || this.selectActiveCon == '婚纱摄影') && this.mode === "bridal"){
      if(this.mode === "bridal"){
        if(this.selectActiveCon == '婚纱摄影' || this.selectActiveCon == '婚纱照' || this.selectActiveCon == '时尚写真' || this.selectActiveCon == '全家福' || this.selectActiveCon == '孕妇摄影' || this.selectActiveCon == '儿童摄影'){
          // 套系详情
          api.push({
            name: ROUTE_NAME.PKG_DETAIL,
            params: {
              pkgId: item.id + ""
            }
          });
        }else{
          // 商品详情
          api.push({
            name: ROUTE_NAME.PRODUCT_DETAIL,
            params: {
              productId: item.id + ""
            }
          });
        }
        
      }else{
        // 商品详情
        api.push({
        name: ROUTE_NAME.PRODUCT_DETAIL,
        params: {
          productId: item.id + ""
        }
      });
      }

      
    } else {
      // api.navigateTo({
      //     url: '/pages/product_detail/main',
      //     query: {
      //         product_id: item.id,
      //     },
      // });
      api.push({
        name: ROUTE_NAME.PRODUCT_DETAIL,
        params: {
          productId: item.id + ""
        }
      });
    }
  }

  //获取品牌列表
  public getBrandList(){
      return store.dispatch('good/getBrand', {
          parent: this.type
      });
  } 

  public async onReachBottom() {
    await this.getProductList(true, false);
  }

  public async beforeRouteEnter(to: Route, from: Route, next: any) {
    const type = to.query.type;
    store.commit("utils/startRequest");
    await Promise.all([
      store.dispatch("shop/getIndexBanners"),
      store.dispatch("shop/getBanners", {
        shopId: to.params.shopId
      }),
      type !== "婚纱摄影" ? store.dispatch("shop/getCategory", { type }) : null
    ]);
    store.commit("utils/endRequest");
    next();
  }
  async created() {
    this.realKey = "";
    this.sortValue = "";
    this.sortName = "";
    this.type = this.$route.query.type;
    this.selectActiveCon = this.type;
    // 获取品牌
    // store.dispatch("good/getBrand", {
    //   parent: this.type
    // });
    // 获取左滑列表
    store.dispatch("good/getSliderList", {
      pid: 0,
      is_view_show: 1
    });

    this.getProductList(true);
    window.addEventListener("reachbottom", this.onReachBottom);
  }
  // 强制更新
  mounted() {
    this.$nextTick(() => {
      this.$forceUpdate();
    });
  }
  public beforeDestroy() {
    window.removeEventListener("reachbottom", this.onReachBottom);
  }
}
</script>

<style lang="less">
@import "../../lib/style/mixins.less";

.shop-category {
  background-color: @color-white;

  .category_feaceBox {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.4);
    z-index: 9;
  }
  .category_boxSize {
    width: 100%;
    height: 100%;
  }
  .category_feace_ul {
    position: absolute;
    top: 0;
    left: 0;
    width: 230rpx;
    height: 95%;
    background-color: #ffffff;
    padding: 30rpx 40rpx;
    padding-right: 20rpx;
    overflow: hidden;
    overflow-y: scroll;
  }

  .feace_title {
    width: 90%;
    font-size: 20px;
    border-bottom: 1px solid #feaaaf;
    margin-bottom: 30px;
  }
  .face_li_box {
    overflow: hidden;
    overflow-y: scroll;
  }
  .face_li {
    padding: 10px 0px;
  }
  .select_active {
    color: #feaaaf;
    border-bottom: 1px solid #feaaaf;
  }
  .face_li_con {
    border-bottom: 1px solid #f2f2f2;
    padding-bottom: 10px;
  }
  .face_li_img {
    width: 11px;
    margin: 12rpx 0rpx 0rpx 20rpx;
  }

  &__filter {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    .text-normal();
    &-type {
      padding: 10px 15px;
      .text-normal();
    }
  }

  .store-info {
    position: relative;
    display: flex;
    padding: 10px 72rpx 0;
    background-color: @primary-color;
    .img-box {
      width: 50px;
      height: 50px;
      image {
        width: 100%;
        height: 100%;
      }
    }
    .info-box {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-left: 10px;
      .mr-left-20 {
        margin-left: 40rpx;
      }
    }
  }
  .goods-box {
    padding: 0 36rpx 10px;
    .good {
      margin-right: -26rpx;
      .item {
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        width: 162px;
        height: 250px;
        margin-top: 10rpx;
        margin-right: 26rpx;
        box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.4);
        border-radius: 14rpx;
        overflow: hidden;
        .img-box {
          position: relative;
          width: 100%;
          height: 158px;
          image {
            width: 100%;
            height: 100%;
            border-radius: 14rpx 14rpx 0 0;
          }
          .label {
            position: absolute;
            bottom: -14rpx;
            left: 10px;
            padding: 4rpx 16rpx;
            border-radius: 14rpx 0 14rpx;
          }
        }
        .info-box {
          padding: 0 10px 10rpx;
          .title-box {
            height: 60rpx;
          }
          .feature-box {
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            margin-top: 10rpx;
            .feature {
              color: rgba(16, 16, 16, 0.57);
            }
          }
        }
      }
    }
  }
  .hot-recommend {
    padding: 10px 51rpx;
  }
}
// 新增
.no-more {
  text-align: center;
  padding: 15px;
  box-sizing: border-box;
  color: #6c6c6c;
  font-size: 14px;
}
</style>
